#include "myusart.h"
#include "usart.h"

MYUSART Serial(&huart1);

MYUSART::MYUSART(UART_HandleTypeDef *huart)
{
    for (uint8_t i = 0; i < RxBuffLength; i++)
    {
        RxBuff[i] = 0;
    }
    RxState = 0;
    length = 0;
    RxData = 0;
    __huart = huart;
    __cpltflag = 0;
    //    HAL_UART_Receive_IT(__huart,&RxData,1);
}

void MYUSART::start_rx()
{
    // HAL_UART_Receive_DMA(__huart, RxBuff, 10);
    HAL_UART_Receive_IT(__huart, &RxData, 1);
}

/// @brief 串口接收数据包函数
/// @param beginwith 帧头
/// @param endwith 帧尾
/// @param requiredatalength 所需数据包的长度
/// @return 返回数据接受状态（1---接收完成/0---接受未完成或接受或失败）
uint8_t MYUSART::ReceivePack(uint8_t beginwith, uint8_t endwith, uint8_t datalength)
{
    if (RxData == beginwith && RxState == 0)
    {

        RxBuff[length++] = RxData;
        //		myprintf("%x",RxData);
        RxState = 1;
    }
    else if (RxState == 1)
    {
        RxBuff[length++] = RxData;
        //		myprintf("%x",RxData);
        if (RxData == endwith && RxState == 1)
        {

            if (length == datalength)
            {
                if (GetFlag() == 0)
                {

                    /*===============定义变量从这里取数据============*/

                    Set();
                    /*==============================================*/
                    //							SendPack(0x2c,0x01,0x5b);
                    //                            myprintf("%s",RxBuff);
                    //                           printf("%s",RxBuff);
                    // printf("\n%x\n",RxDataStr.sort);
                    memset(RxBuff, 0, length);
                    length = 0;
                    RxState = 0;
                    RxData = 0;
                    start_rx();
                    //                            UART_Start_Receive_IT(__huart,&RxData,1);

                    // SendDate(0x2C,0x5B,0x01);//打开视觉识别（在对垃圾处理完成后再调用，而不是这里）

                    return 1;
                }
                else
                { // 未处理完，不接受数据，丢包
                    memset(RxBuff, 0, length);
                    RxState = 0;
                    RxData = 0;
                    length = 0;
                }
            }
            else
            { // 数据不对，丢包
                memset(RxBuff, 0, length);
                RxState = 0;
                RxData = 0;
                length = 0;
            }
        }
    }

    start_rx();

    //    UART_Start_Receive_IT(__huart,&RxData,1);

    return 0;
}

/// @brief 串口DMA接收数据包函数
/// @param beginwith 帧头
/// @param endwith 帧尾
/// @param requiredatalength 所需数据包的长度
/// @return 返回数据接受状态（1---接收完成/0---接受未完成或接受或失败）
void MYUSART::ReceivePack_DMA(uint8_t beginwith, uint8_t endwith, uint8_t datalength)
{
    if (RxBuff[0] == beginwith)
    {
        while (RxBuff[length] != endwith && length < datalength)
        {
            rxdata[length] = RxBuff[length];
            length++;
        }
        if (length > datalength)
        {
            // 数据不对，丢包
            memset(RxBuff, 0, RxBuffLength);
            memset(rxdata, 0, RxBuffLength);
            length = 0;
        }
        return;
    }
    else
    {
        // 数据不对，丢包
        memset(RxBuff, 0, RxBuffLength);
        RxState = 0;
        RxData = 0;
        length = 0;
    }
}

/// @brief 串口打包发送函数
/// @param beginwith 帧头
/// @param endwith 帧尾
/// @param value 数据
void MYUSART::SendPack(uint8_t beginwith, uint8_t endwith, uint8_t value)
{
    uint8_t temp[3];
    uint8_t i = 0, j = 0;
    uint8_t floatVariable = value;
    uint8_t *pdata = (uint8_t *)&floatVariable;

    temp[0] = beginwith; // 数据包头

    for (i = 0; i < 3; i++)
    {
        temp[i + 1] = *pdata++; // float转BYTE
    }
    temp[2] = endwith; // 数据包尾

    for (j = 0; j < 3; j++)
    {
        HAL_UART_Transmit(__huart, &temp[j], 1, HAL_MAX_DELAY);
    }
}
/// @brief 串口打包发送函数(发送数组)
/// @param *txbuff 数组
/// @param packsize 包的大小
void MYUSART::SendPack(uint8_t *txbuff, uint8_t packsize)
{

    // for (uint8_t j = 0; j < packsize; j++)
    // {
    //     HAL_UART_Transmit(__huart, &txbuff[j], 1, HAL_MAX_DELAY);
    // }
    HAL_UART_Transmit_DMA(__huart, txbuff, packsize);
}

void MYUSART::Set(void)
{
    // PSW |= (0x01<<usartcplt);
    __cpltflag = 1;
}
void MYUSART::Reset(void)
{
    // PSW &= (0xFE<<usartcplt);
    __cpltflag = 0;
}

bool MYUSART::GetFlag(void)
{
    // return PSW & (0x01<<usartcplt);
    return __cpltflag;
}
// int MYUSART::fputc(int ch,FILE *f)
// {
//     HAL_UART_Transmit(&huart1,(uint8_t *)&ch,1,HAL_MAX_DELAY);
//     return ch;
// }

void MYUSART::myprintf(char *fmt, ...)
{
    uint8_t tempbuff[256];
    uint16_t i;
    va_list ap;
    va_start(ap, fmt);
    vsprintf((char *)tempbuff, fmt, ap);
    va_end(ap);

    for (i = 0; i < strlen((char *)tempbuff); i++)
    {
        while (!__HAL_UART_GET_FLAG(__huart, UART_FLAG_TXE))
            ;
        (*__huart).Instance->DR = tempbuff[i];
    }
    // HAL_UART_Transmit_DMA(__huart, tempbuff, strlen((char *)tempbuff));
}

/*
功能：计算一组数据的校验和
输入： buffer  待校验数据
       size    待校验数据个数
输出： 校验值
*/
uint8_t MYUSART::getCheckSum(uint8_t *buffer, uint8_t size)
{
    uint8_t i;
    uint16_t sum = 0;
    for (i = 0; i < size; i++)
    {
        sum += buffer[i]; // 计算累加值
    }
    return (sum & 0xFF); // 返回校验和
}
